var express = require('express');
var router = express.Router();
var  connection = require('../mysql')
const {packRes} = require('../utils/packRes')

router.get('/', function (req, res, next) {
  var limit = parseInt(req.query.limit) || 5;
  var page = parseInt(req.query.page) || 1;
  var offset = (page - 1) * limit;
  console.log(1111111111)
  connection.query('SELECT COUNT(*) as total FROM user', function (error, results, fields) {
    if (error) throw error;
    const total = results[0].total;
    console.log('total',total)

    connection.query('SELECT * FROM user LIMIT ?, ?', [offset, limit], function(error, results, fields) {
      if (error) throw error;
      res.status(200).send(packRes(200, {results, total, limit, page}));
    });
  });
});


// 注册接口，需要提供用户名、密码、手机号、邮箱、昵称和角色信息
router.post('/register', function(req, res, next) {
  // 解构请求体中的参数
  const { username, password, iphone, email, nickname, role } = req.body;
  // 构造查询语句
  const sql = `SELECT * FROM user WHERE username='${username}'`;
  // 执行查询操作
  connection.query(sql, function(error, results, fields) {
    if (error) {
      console.error(error);
      return res.status(200).send(packRes(500,'','服务器错误，请联系管理员'));
    }
    if (results.length !== 0) {
      return res.status(200).send(packRes(401,'','账号已存在'));
    }
    // 构造插入语句
    const insertSql = `INSERT INTO user (username, password, iphone, email, nickname, role) VALUES ('${username}', '${password}', '${iphone}', '${email}', '${nickname}', '${role}')`;
    // 执行插入操作
    connection.query(insertSql, function(error, results, fields) {
      if (error) {
        console.error(error);
        return res.status(200).send(packRes(500,'','服务器错误，请联系管理员'));
      }
      res.status(200).json(packRes(200,{
        ...req.body
      }));
    });
  });
});



// 登录接口
router.post('/login', function(req, res, next) {
  const { username, password } = req.body;
  console.log(11111111,username)
  // 构造查询语句
  const sql = `SELECT * FROM user WHERE username='${username}' AND password='${password}'`;

  // 执行查询操作
  connection.query(sql, function(error, results, fields) {
    if (error) {
      console.error(error);
      return res.status(200).send(packRes(500,'','服务器错误，请联系管理员'));
    }

    if (results.length === 0) {
      return res.status(200).send(packRes(401,'','账号或者密码错误'));
    }

    // 返回用户所有信息和 token
    res.status(200).json(packRes(200,{
      ...results[0]
    }));
  });
});


// 账号删除接口以post方式处理
router.post('/delete-account', function(req, res, next) {
  const { id } = req.body;
console.log(id);
  // 执行删除操作
  const sql = `DELETE FROM user WHERE id=${id}`;
  connection.query(sql, function(error, results, fields) {
    if (error) {
      console.error(error);
      return res.status(500).send('服务器错误，请联系管理员');
    }

    return res.status(200).send(packRes(200,'账号删除成功'));
  });
});

// 账号修改接口以post方式处理
router.post('/update-account', function(req, res, next) {
  let arr = ['username', 'password', 'iphone', 'email', 'nickname', 'role']
  let sql = `UPDATE user SET`;
  let stArr = []
  for (let i = 0; i < arr.length; i++) {
    const key = arr[i];
    if (req.body[key]) {
      stArr.push(` ${key}='${req.body[key]}'`)
    }
  }
  sql+=stArr.join(',')

  // 加入条件
  sql += ` WHERE id=${req.body.id}`;
  console.log(1111111111,sql)
  // 执行修改操作
  connection.query(sql, function(error, results, fields) {
    if (error) {
      console.error(error);
      return res.status(500).send('服务器错误，请联系管理员');
    }

    return res.status(200).send(packRes(200,'账号修改成功'));
  });
});

// 查询所有账号接口
router.get('/accounts', function(req, res, next) {
  // 构造查询语句
  const sql = `SELECT * FROM user`;
  // 执行查询操作
  connection.query(sql, function(error, results, fields) {
    if (error) {
      console.error(error);
      return res.status(500).send('服务器错误，请联系管理员');
    }
    // 返回账号信息
    res.json({
      accounts: results
    });
  });
});

module.exports = router;
